package com.hyacinth.utils.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class SocketUtils {
	
	private static final Logger log = LoggerFactory.getLogger(SocketUtils.class);
	
	// 发送报文异常时返回的提示信息
	public static final String SEND_EXCEPTION = "exception_send";
	
	/**
	 * 向指定ip和端口号的地址发送请求报文，获取返回报文后关闭连接
	 * @param content 报文内容
	 * @param ip 对方ip
	 * @param port 对方端口
	 * @param reqCharSet 请求报文编码格式
	 * @param rspCharSet 返回报文编码格式
	 * @return
	 */
	public static String sendMsg(String content, String ip, int port, String reqCharSet, String rspCharSet) {
		Socket client = null;
		PrintWriter printWriter = null;
		InputStreamReader streamReader = null;
		BufferedReader reader = null;
		try {
			
			// 向服务器端发送请求，服务器IP地址和服务器监听的端口号
	        client = new Socket(ip, port);

	        // 通过printWriter 来向服务器发送消息
	        printWriter = new PrintWriter(new OutputStreamWriter(client.getOutputStream(), reqCharSet));
	        log.debug("连接已建立...ip=" + ip + ", port=" + port);
			
	        
	        // 发送消息
	        //log.debug("即将发送的报文:"+content);
	        printWriter.println(content);
	        printWriter.flush();
	        log.debug("报文发送成功");
	        

	        // InputStreamReader是低层和高层串流之间的桥梁 client.getInputStream()从Socket取得输入串流
	        streamReader = new InputStreamReader(client.getInputStream(), rspCharSet);

	        // 链接数据串流，建立BufferedReader来读取，将BufferReader链接到InputStreamReder
	        reader = new BufferedReader(streamReader);
	        
	        StringBuilder sb = new StringBuilder();
            String line = "";
            while ((line = reader.readLine()) != null) {
            	sb.append(line);
            }
            String rspStr = sb.toString();
            //log.debug("返回的报文:"+rspStr);
            log.debug("报文接收成功");
            
            return rspStr;
	    } catch (Exception e) {
	    	log.error("发送报文时发生异常，ip="+ip+", port="+port, e);
	    	return SEND_EXCEPTION;
	    } finally {
	    	try {
                if (reader != null) {
                    reader.close();
                }
                if (streamReader != null) {
                    streamReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
                if (client != null) {
                    client.close();
                }
            } catch (Exception ee) {
	    		log.error("关闭时发生异常，ip="+ip+", port="+port, ee);
	    	}
	    }
	}

}
